package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"manage/managerpc/internal/svc"
	"manage/managerpc/managerpc"
	"manage/models/cache"
	"manage/models/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManageListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManageListLogic {
	return &ManageListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ManageListLogic) ManageList(in *managerpc.ManageListRequest) (*managerpc.ManageListResponse, error) {
	// todo: add your logic here and delete this line

	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var manage []mysql.Manage
	key := fmt.Sprintf("problemHotList")
	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		mysql.DB.Debug().Limit(10).Order("hot desc").Find(&manage)
		marshal, _ := json.Marshal(manage)

		cache.Rdb.Set(l.ctx, key, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(result), &manage)
	}

	mysql.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Order("created_at desc").Find(&manage)
	var manageList []*managerpc.ManageList
	for _, m := range manage {
		list := managerpc.ManageList{
			ManageId:   int64(m.ID),
			UserId:     m.UserId,
			Image:      m.Image,
			ManageName: m.ManageName,
			Num:        int64(m.Num),
			CreatedAt:  m.CreatedAt.Format(time.DateTime),
		}
		manageList = append(manageList, &list)
	}
	return &managerpc.ManageListResponse{
		List: manageList,
	}, nil
}
